package cn.schoolwow.quickdao.module.database.dql.condition.flow.update;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dql.condition.domain.SQLFragmentEntry;
import cn.schoolwow.quickdao.module.database.dql.parent.domain.QueryContext;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class SetUpdateFragmentFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QueryContext queryContext = (QueryContext) flowContext.checkData("queryContext");
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        if(queryContext.queryOption.queryUpdateOption.setList.isEmpty()){
            return;
        }
        StringBuilder sqlBuilder = new StringBuilder("set ");
        for(SQLFragmentEntry fieldFragmentEntry: queryContext.queryOption.queryUpdateOption.setList){
            if(null!=fieldFragmentEntry.field&&fieldFragmentEntry.fragment.contains("{}")){
                Property property = queryContext.queryOption.queryTableOption.entity.getPropertyByFieldNameOrColumnName(fieldFragmentEntry.field);
                if(null==property){
                    sqlBuilder.append(fieldFragmentEntry.fragment.replace("{}", fieldFragmentEntry.field));
                }else if(null==property.function){
                    sqlBuilder.append(fieldFragmentEntry.fragment.replace("{}", quickDAOConfig.databaseContext.databaseProvider.escape(property.column)));
                }else{
                    sqlBuilder.append(fieldFragmentEntry.fragment.replace("{}", property.column).replace("?", property.function));
                }
            }else{
                sqlBuilder.append(fieldFragmentEntry.fragment);
            }
            sqlBuilder.append(fieldFragmentEntry.concat);
        }
        int deleteLength = queryContext.queryOption.queryUpdateOption.setList.get(queryContext.queryOption.queryUpdateOption.setList.size()-1).concat.length();
        sqlBuilder.delete(sqlBuilder.length()-deleteLength, sqlBuilder.length());
        queryContext.set = sqlBuilder.toString();

        queryContext.setParameters = queryContext.queryOption.queryUpdateOption.setParameterList;
    }

    @Override
    public String name() {
        return "拼接更新语句片段";
    }

}
